package com.atguigu.flinkSideOutput;


import com.atguigu.been.WaterSensor;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;


//split算子可以把一个流分成两个流, 从1.12开始已经被移除了.
// 官方建议我们用侧输出流来替换split算子的功能.
//需求: 采集监控传感器水位值，将水位值高于5cm的值输出到side output

public class SideOutput_split {
    public static void main(String[] args) throws Exception {
        //1.流的执行环境
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);

        //2.获取数据
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);

        //3.对数据进行处理，封装成WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        SingleOutputStreamOperator<WaterSensor> process = waterSensorDStream.keyBy(WaterSensor::getId).process(new ProcessFunction<WaterSensor, WaterSensor>() {
            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {
                if (value.getVc() <= 5) {
                    out.collect(value);
                } else {
                    ctx.output(new OutputTag<WaterSensor>("up5cm") {}, value);
                }

            }
        });

        process.print("正常");
        process.getSideOutput(new OutputTag<WaterSensor>("up5cm"){}).print("警告");


        senv.execute();
    }
}
